package com.sqly.doc.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.gcacace.signaturepad.views.SignaturePad;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.sqly.doc.ImageLook;
import com.sqly.doc.R;
import com.sqly.doc.menu.camera.CameraChoose;
import com.sqly.doc.pojo.RetMsg;
import com.sqly.doc.view.StringUtils;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.entity.ContentType;

public class WriteActivity extends Activity {

	private static final int REQUEST_EXTERNAL_STORAGE = 1;
	private static String[] PERMISSIONS_STORAGE = { Manifest.permission.WRITE_EXTERNAL_STORAGE };
	private SignaturePad mSignaturePad;
	private Button mClearButton;
	private Button queDing, quxiao;
	private ImageView result_img;
	private int count = 0;// 写字的个数
	private Bitmap pre;// 之前的bitmap
	private Button look;
	private Bitmap result;// 最终的bitmap
	String imageType = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// verifyStoragePermissions(this);
		setContentView(R.layout.write_dialog);
		quxiao = (Button) findViewById(R.id.quxiao);
		quxiao.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		imageType = getIntent().getStringExtra("imageType");
		queDing = (Button) findViewById(R.id.queding);
		queDing.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				try {
					if(null != getIntent().getStringExtra("class") && !"team_member_qm.class".equals(getIntent().getStringExtra("class"))){
						uploadImg();
					}else{
						Bitmap signatureBitmap = mSignaturePad.getSignatureBitmap();
						signatureBitmap = CreateBitmap.zoomImg(signatureBitmap, 1, 1);
						result =signatureBitmap;
						Intent intent = new Intent(WriteActivity.this, getIntent().getStringExtra("class").getClass());
						ByteArrayOutputStream baos = new ByteArrayOutputStream();
						result.compress(Bitmap.CompressFormat.PNG, 100, baos);
						byte[] bitmapByte = baos.toByteArray();
						intent.putExtra("bitmap", bitmapByte);
						setResult(8, intent);
						WriteActivity.this.finish();
					}
				} catch (Exception e) {
					// TODO: handle exception
					System.out.println(e.toString());
				}
			}
		});
		result_img = (ImageView) findViewById(R.id.result);
		result_img.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(WriteActivity.this, ImageLook.class);
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				pre.compress(Bitmap.CompressFormat.PNG, 100, baos);
				byte[] bitmapByte = baos.toByteArray();
				intent.putExtra("bitmap", bitmapByte);
				startActivity(intent);
			}
		});
		mSignaturePad = (SignaturePad) findViewById(R.id.signature_pad);
		mSignaturePad.setOnSignedListener(new SignaturePad.OnSignedListener() {
			@Override
			public void onStartSigning() {

			}

			@Override
			public void onSigned() {
				mClearButton.setEnabled(true);
			}

			@Override
			public void onClear() {
				mClearButton.setEnabled(false);
			}
		});

		mClearButton = (Button) findViewById(R.id.clear_button);
		mClearButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				mSignaturePad.clear();
			}
		});
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	public void onRequestPermissionsResult(int requestCode,
			String permissions[], int[] grantResults) {
		switch (requestCode) {
			case REQUEST_EXTERNAL_STORAGE: {
				// If request is cancelled, the result arrays are empty.
			}
		}
	}

	public File getAlbumStorageDir(String albumName) {
		// Get the directory for the user's public pictures directory.
		File file = new File(Environment.getExternalStorageDirectory(),	albumName);
		if (!file.mkdirs()) {
			Log.e("SignaturePad", "Directory not created");
		}
		return file;
	}

	public void saveBitmapToJPG(Bitmap bitmap, File photo) throws IOException {
		Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(newBitmap);
		canvas.drawColor(Color.WHITE);
		canvas.drawBitmap(bitmap, 0, 0, null);
		OutputStream stream = new FileOutputStream(photo);
		newBitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
		stream.close();
	}

	public boolean addJpgSignatureToGallery(Bitmap signature) {
		boolean result = false;
		try {
			File photo = new File(getAlbumStorageDir("SignaturePad"), String.format("Signature_%d.jpg", System.currentTimeMillis()));
			saveBitmapToJPG(signature, photo);
			scanMediaFile(photo);
			result = true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	private void scanMediaFile(File photo) {
		Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		Uri contentUri = Uri.fromFile(photo);
		mediaScanIntent.setData(contentUri);
		WriteActivity.this.sendBroadcast(mediaScanIntent);
	}

	public boolean addSvgSignatureToGallery(String signatureSvg) {
		boolean result = false;
		try {
			File svgFile = new File(getAlbumStorageDir("SignaturePad"), String.format("Signature_%d.svg", System.currentTimeMillis()));
			OutputStream stream = new FileOutputStream(svgFile);
			OutputStreamWriter writer = new OutputStreamWriter(stream);
			writer.write(signatureSvg);
			writer.close();
			stream.flush();
			stream.close();
			scanMediaFile(svgFile);
			result = true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	//上传图片文件的操作
	public void uploadImg() {
		StringBuilder urlParams = new StringBuilder();
		String url = HttpUrl.SaveBrqmImage;
		if(null != imageType && "img1".equals(imageType)){
			url = HttpUrl.SaveYsqmImage;
		}
		if (NetWorkUtils.isNetworkConnected(WriteActivity.this)) {  //////网络存在
			RequestParams ps = new RequestParams();

			Bitmap signatureBitmap = mSignaturePad.getSignatureBitmap();
			signatureBitmap = CreateBitmap.zoomImg(signatureBitmap, 1, 1);
			result =signatureBitmap;
			final ByteArrayOutputStream baos = new ByteArrayOutputStream();
			result.compress(Bitmap.CompressFormat.PNG, 100, baos);
			final byte[] bis = baos.toByteArray();
			Bitmap bmp = BitmapFactory.decodeByteArray(bis, 0, bis.length);
			Bitmap bb = CreateBitmap.zoomImg(bmp, 1, 1);
			String qmpic = CreateBitmap.saveMyBitmap(bb);

			try {
				ps.put("img", new File(Environment.getExternalStorageDirectory() + "/" + qmpic + ".jpg"), ContentType.IMAGE_JPEG.getMimeType());
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}

			String cardnum = getIntent().getStringExtra("cardnum"),
					tabId = getIntent().getStringExtra("tabId"),
					tabType = getIntent().getStringExtra("tabType");
//			ps.add("token", SharedPreferencesUtils.getParam(WriteActivity.this, "token", "").toString());
//			ps.add("cardnum", cardnum);
//			ps.add("tabId", tabId);
//			ps.add("tabType", tabType);
//			ps.add("type", "2");
			urlParams.append("token=").append(SharedPreferencesUtils.getParam(this, "token", "").toString()).append("&");
			urlParams.append("cardnum=").append(cardnum).append("&");
			urlParams.append("tabId=").append(tabId).append("&");
			urlParams.append("tabType=").append(tabType).append("&");
			urlParams.append("type=").append("2");

			AsyncHttpClient client = new AsyncHttpClient();
			ps.setUseJsonStreamer(false);
			ps.setForceMultipartEntityContentType(true);
			client.setURLEncodingEnabled(true);
			Log.i("uploadurl:",UserClient.getUploadAbsoluteUrl2(url + "?" + urlParams.toString()));
			client.post(this, UserClient.getUploadAbsoluteUrl2(url + "?" + urlParams.toString()), ps, new AsyncHttpResponseHandler() {
				@Override
				public void onSuccess(int statusCode, Header[] headers, byte[] response) {
					String content = new String(response);
					Log.i("签名已保存", content);
					RetMsg ret = JSON.parseObject(content, RetMsg.class);
					if (ret.getCode().equals("200")) {
						JSONObject j = JSON.parseObject(ret.getRd());
//							Intent intent = new Intent(WriteActivity.this, getIntent().getStringExtra("class").getClass());
//							intent.putExtra("img_record_id", j.getString("id"));
//							intent.putExtra("bitmap", bitmapByte);
//							setResult(119, intent);
//							finish();
						Intent intent = new Intent(WriteActivity.this, getIntent().getStringExtra("class").getClass());
						intent.putExtra("bitmap", bis);
						intent.putExtra("record_id", j.getString("id"));
						if(null != imageType && "img1".equals(imageType)){
							setResult(8, intent);
						}else{
							setResult(9, intent);
						}
						WriteActivity.this.finish();
					} else {
						SweetAlertDialogUtil.ErrorDialogNoFinish(WriteActivity.this, "错误提示", ret.getInfo(), "确定");
					}
				}

				@Override
				public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
					MyToastUtil.ShowToast(WriteActivity.this, "保存失败");
				}
			});
		} else {  //网络不存在
			MyToastUtil.ShowToast(WriteActivity.this, "保存失败");
		}
	}

	/**
	 * Checks if the app has permission to write to device storage
	 * <p/>
	 * If the app does not has permission then the user will be prompted to
	 * grant permissions
	 * 
	 * @param activity
	 *            the activity from which permissions are checked
	 */
	// public static void verifyStoragePermissions(Activity activity) {
	// // Check if we have write permission
	// int permission = ActivityCompat.checkSelfPermission(activity,
	// Manifest.permission.WRITE_EXTERNAL_STORAGE);
	//
	// if (permission != PackageManager.PERMISSION_GRANTED) {
	// // We don't have permission so prompt the user
	// ActivityCompat.requestPermissions(
	// activity,
	// PERMISSIONS_STORAGE,
	// REQUEST_EXTERNAL_STORAGE
	// );
	// }
	// }
}
